package com.imooc.security.browser;

import com.imooc.security.browser.entity.MyUserDetailsImpl;
import com.imooc.security.data.pojo.dto.UserResponseDTO;
import com.imooc.security.data.pojo.response.CommonResponseDto;
import com.imooc.security.feign.DataFeign;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 自定义的UserDetailsService用户名密码校验接口实现
 *
 * @author Created By Houce
 * @date 2020-07-22 15:56
 */
@Component
public class MyUserDetailServiceImpl implements UserDetailsService {

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Resource
    private DataFeign dataFeign;

    /**
     * 根据用户名查找用户信息获取密码交给SpringSecurity框架，框架会根据提供的加密密码和前端输入密码做校验
     * @param username 用户名
     * @return 用户信息
     * @throws UsernameNotFoundException 未查询到用户异常
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        final CommonResponseDto<UserResponseDTO> userResponseDtoCommonResponseDto = dataFeign.queryUserByUid(username);
        final UserResponseDTO userResponseDTO = userResponseDtoCommonResponseDto.getBody();
        final MyUserDetailsImpl myUserDetails = new MyUserDetailsImpl();
        BeanUtils.copyProperties(userResponseDTO,myUserDetails);
        myUserDetails.setAuthorities(AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
        return myUserDetails;
    }
}
